﻿using System;
using System.Linq;
using ZilLion.Core.ConfigManager.Cache;

namespace ZilLion.Core.ConfigManager.Manager
{
    public static class ZilLionConfigurationManager
    {
        /// <summary>
        ///     构造函数
        /// </summary>
        static ZilLionConfigurationManager()
        {
            ConfigurationInstanceCache.Instance()
                .CachingConfigInstance<SysConfig>("app.config");
            //创建appconfig 实例
        }


        /// <summary>
        ///     获取制定config实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetConfigInstance<T>() where T : class, new()
        {
            var instance = ConfigurationInstanceCache.Instance().GetConfigInstance<T>();
            if (instance == null) throw new Exception($"获取配置类型{typeof(T).FullName}出错，请检查配置文件是否正确配置");
            return instance;
        }


        /// <summary>
        ///     保存制定config
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static void SaveConfig<T>(T config) where T : class
        {
            ConfigurationInstanceCache.Instance().SaveConfig(config);
        }

        /// <summary>
        ///     获取系统config值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetSysSettingValue(string key)
        {
            return ConfigurationInstanceCache.Instance().GetConfigInstance<SysConfig>().GetAppSetting(key);
        }

        #region 注册自定义provider策略（覆盖预编译的标签）

        public static void RegisterCustomPoviderstrategy(Type configType, Type providerType)
        {
            if (
                ConfigurationInstanceCache.Instance()
                    .ConfigCustomProviderCache.Keys.Any(x => x.FullName == configType.FullName))
            {
                var first = ConfigurationInstanceCache.Instance()
                    .ConfigCustomProviderCache.Keys.FirstOrDefault(x => x.FullName == configType.FullName);
                if (first != null)
                    ConfigurationInstanceCache.Instance()
                        .ConfigCustomProviderCache[first] = providerType;
            }
            else
            {
                ConfigurationInstanceCache.Instance()
                    .ConfigCustomProviderCache.Add(configType, providerType);
            }
        }

        #endregion
    }
}